package com.gonsin.gnews;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.gonsin.gnews.annotations.*;
import com.gonsin.gnews.annotations.model.*;
import com.gonsin.gnews.annotations.services.SenderService;
import com.gonsin.gnews.annotations.services.TemplateService;
import com.gonsin.i18n.logic.T;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Api(tags = "消息模板相关接口")
@RestController
@RequestMapping("/api/news")
public class NewsController  {

    @Autowired private INewsService newsService;
    @Autowired private TemplateService newsTemplateService;
    @Autowired private SenderService senderService;
    @Autowired private NewsConfig newsConfig;

    @ApiOperationSupport(order = 23000)
    @ApiOperation("消息模板 - 查询一个")
    @GetMapping("/template")
    public GNewsResponseResult<NewsTemplateBean> findTemplate(
            @ApiParam("消息模板主键") @RequestParam("newsTemplateKey") String newsTemplateKey){
        NewsTemplateBean bo = newsTemplateService.getTemplate(newsTemplateKey);
        return GNewsResponseResult.result(bo);
    }

    @ApiOperationSupport(order = 23001)
    @ApiOperation("消息模板 - 查询列表")
    @GetMapping("/templates")
    public GNewsResponseResult<GNewsPageResult<NewsTemplateBean>> findTemplates(
            @ApiIgnore HttpSession session,
            GNewsPageRequest pagePo, NewsTemplateSearchPo searchPo){
        String edificeKey = (String) session.getAttribute("EDIFICE_KEY");
        GNewsPageResult<NewsTemplateBean> bo = newsTemplateService.searchTemplates(edificeKey, searchPo, pagePo);
        return GNewsResponseResult.result(bo);
    }

    @ApiOperationSupport(order = 23002)
    @ApiOperation("消息模板 - 删除")
    @PostMapping("/templates/delete")
    public GNewsResponseResult<Void> deleteTemplate(
            @ApiIgnore HttpSession session,
            @ApiParam("模板主键") @RequestParam("newsTemplateKey") String newsTemplateKey){
        List<String> keys = Arrays.stream(newsTemplateKey.split(",")).collect(Collectors.toList());
        newsTemplateService.deleteNewsTemplate(keys);
        return GNewsResponseResult.simpleResult();
    }


    @ApiOperationSupport(order = 23003)
    @ApiOperation("消息模板 - 添加")
    @PostMapping("/templates/save")
    public GNewsResponseResult<Void> saveTemplate(
            @ApiIgnore HttpSession session,
            @ApiParam("模板的类型") @RequestParam("templateKey") String templateKey,
            @ApiParam("模板结构") @RequestParam("json") String json){
        NewsTemplatePo po = new Gson().fromJson(json, NewsTemplatePo.class);

        // TODO 这里涉及到多租户的概念，目前是直接从session获取，但是日后这一点需要优化。
        String edificeKey = (String) session.getAttribute("EDIFICE_KEY");
        newsTemplateService.addNewsTemplate(edificeKey, templateKey, po);
        return GNewsResponseResult.simpleResult();
    }


    @ApiOperationSupport(order = 23003)
    @ApiOperation("消息模板 - 修改")
    @PostMapping("/templates/update")
    public GNewsResponseResult<Void> updateTemplate(
            @ApiIgnore HttpSession session,
            @ApiParam("模板消息主键") @RequestParam("newsTemplateKey") String newsTemplateKey,
            @ApiParam("模板结构") @RequestParam("json") String json){
        NewsTemplatePo po = new Gson().fromJson(json, NewsTemplatePo.class);
        newsTemplateService.updateNewsTemplate(newsTemplateKey, po);
        return GNewsResponseResult.simpleResult();
    }

    @ApiOperationSupport(order = 23004)
    @ApiOperation("消息模板 - 查询可用变量及含义")
    @GetMapping("/templates/keys")
    public GNewsResponseResult<List<NewsStructPo>> findTemplatesParams(
            @ApiParam("用户类型") @RequestParam(value = "userType", defaultValue = "admin", required = false) String userType,
            @ApiIgnore HttpSession session){
        List<NewsStructPo> structPos = newsConfig.getAllNewsStruct(userType);
        structPos = structPos.stream().map(NewsStructPo::new)
                .peek(n -> {
                    n.setTitle(T.t(n.getTitle()));
                    n.setName(T.t(n.getName()));
                    for(NewsStructPo.NewsTemplateParams p : n.getParams()){
                        p.setKey(T.t(p.getKey()));
                    }
                })
                .collect(Collectors.toList());
        return GNewsResponseResult.result(structPos);
    }


    @ApiOperationSupport(order = 23007)
    @ApiOperation("消息模板 - 启用|禁用")
    @GetMapping("/templates/enable")
    public GNewsResponseResult<Void> enableTemplates(
            @ApiIgnore HttpSession session,
            @ApiParam("模板主键") @RequestParam("newsTemplateKey") String newsTemplateKey,
            @ApiParam("启用或禁用") @RequestParam("enable") boolean enable){

        newsTemplateService.enableTemplate(newsTemplateKey, enable);
        return GNewsResponseResult.simpleResult();
    }

    @ApiOperation("消息模板 - 上移")
    @GetMapping("/templates/moveUp")
    public GNewsResponseResult<NewsTemplateBean> moveUpNewsTemplate(
            @ApiParam("模板主键") @RequestParam("newsTemplateKey") String newsTemplateKey){
        NewsTemplateBean result = newsTemplateService.moveUpNewsTemplate(newsTemplateKey);
        return GNewsResponseResult.result(result);
    }

    @ApiOperation("消息模板 - 下移")
    @GetMapping("/templates/moveDown")
    public GNewsResponseResult<NewsTemplateBean> moveDownNewsTemplate(
            @ApiParam("模板主键") @RequestParam("newsTemplateKey") String newsTemplateKey){
        NewsTemplateBean result = newsTemplateService.moveDownNewsTemplate(newsTemplateKey);
        return GNewsResponseResult.result(result);
    }

    @ApiOperationSupport(order = 23008)
    @ApiOperation("发送器 - 查询所有发送器")
    @GetMapping("/senders")
    public GNewsResponseResult<List<GNewsSenderDescriber>> findSenders(){
        List<GNewsSenderDescriber> bo = senderService.findAll();
        List<GNewsSenderDescriber> result = bo.stream().map(GNewsSenderDescriber::new).collect(Collectors.toList());
        result.forEach(n -> {
            n.setPlatformName(T.t(n.getPlatformName()));
        });
        return GNewsResponseResult.result(result);
    }

}
